import React, { Component } from 'react'
import From from './From'
import ListItems from './ListItems'
import Dialog from './Dialog'
import "./common.scss"
import "./todo.css"


export default class Todolist extends Component {

  constructor(){
    super();
    //初次的state
    this.state={
      keyword : '',
      showEdit : false,
      currentTodo : {},
      datalist : [
        {
          id : 1,
          name : "太难了"
        },{
          id : 2,
          name : "确实如此"
        },{
          id : 1,
          name : "不难"
        },{
          id : 1,
          name : "说的是"
        },
      ]
    }
  }

  handleAdd(name){
    this.state.datalist.push({
      id : new Date().getTime(),
      name : name
    })
    this.setState({})
  }

  handleDel(id){
    console.log(id);
    this.state.datalist.find((item,index)=>{
      if(item.id === id){
        this.state.datalist.splice(index,1);
        return true;
      }
    })
    this.setState({});
  }

  handleEdit(id){
    let current = this.state.datalist.find((item,index)=>{
      if(item.id === id){
        return true;
      }
    })

    this.setState({
      showEdit : true,
      currentTodo : current
    })
  }

  handleSearch(name){
    this.state.keyword=name;
    this.setState({})
  }

  handleSubmit=()=>{
    let con = this.refs.name.value;
    this.state.datalist.find((item,index)=>{
      if(item.id === this.state.currentTodo.id){
        this.state.datalist[index].name = con;
        return true;
      }
    })
    this.setState({
      showEdit : false,
      currentTodo : {}
    })
  }

  handleCancel=()=>{
    this.setState({
      showEdit : false,
      currentTodo : {}
    })
  }

  render() {

    let edit = <Dialog title="编辑">
      <input type="text" ref="name" defaultValue={this.state.currentTodo.name} /><br/>
      <button onClick={this.handleSubmit}>提交</button>
      <button onClick={this.handleCancel}>取消</button>
    </Dialog>

    let list = this.state.datalist.filter((item,index)=>{
      return item.name.indexOf(this.state.keyword) > -1;
    })

    return (
      <div>
        <From add={(name)=>{this.handleAdd(name)}} search={(name)=>{
          this.handleSearch(name)
        }}>
        </From>
        <ListItems list={list} edit={(id)=>{this.handleEdit(id)}} del={(id)=>{this.handleDel(id)}}></ListItems>
        {
          this.state.showEdit ? edit : ''
        }
      </div>
    )
  }
}
